class FriendshipController < ApplicationController
  before_filter :protect, :setup_friends
  #发送一个建立朋友关系的请求
  def create
    Friendship.request(@login_user,@friend)
    UserMailer.deliver_friend_request(
      :user => @login_user,
      :friend => @friend,
      :user_url => profile_for(@login_user),
      :accept_url => url_for(:action => :accept, :id => @login_user.username),
      :decline_url => url_for(:action => :decline, :id => @friend.username)
    )
    redirect_to profile_for(@friend)
  end
  
  def accept
    if @login_user.requested_friends.include?(@friend)
      Friendship.accept(@login_user,@friend)
      flash[:notice] = "成功与#{@friend.username}成为好友"
    else
      flash[:notice] = "无效的请求"
    end
    redirect_to profile_for(@login_user)
  end
  
  def decline
    if @login_user.requested_friends.include?(@friend)
      Friendship.breakup(@login_user,@friend)
      flash[:notice] = "成功拒绝#{@friend.username}的好友请求"
    else
      flash[:notice] = "#{@friend.username}并未向您申请为好友"
    end
    redirect_to profile_for(@login_user)
  end
  
  def cancel
    if @login_user.pending_friends.include?(@friend)
      Friendship.breakup(@login_user,@friend)
      flash[:notice] = "成功取消好友请求"
    else
      flash[:notice] = "并未向#{@friend.username}申请为好友"
    end
    redirect_to profile_for(@login_user)
  end
  
  def delete
    if @login_user.friends.include?(@friend)
      Friendship.breakup(@login_user,@friend)
      flash[:notice] = "成功删除好友关系"
    else
      flash[:notice] = "并未和#{@friend.username}建立好友关系"
    end
    redirect_to profile_for(@login_user)
  end
  
  private
  
  def setup_friends
    @friend = User.find_by_username(params[:id])
  end
end
